/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package giormi;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.swing.JOptionPane;
import javax.swing.JTable;
/**
 *
 * @author giorgio
 */
public class searchcustomer {

    private String c_name;
    private JTable ctable;
    
    
    public searchcustomer(String c_name,JTable ctable){
        this.c_name = c_name;
        this.ctable = ctable;
    }
    private Connection conn;
    private String SQLStatement;
    private String URL;
    private Statement stmt;
    public ResultSet rset;    
    
    public void connect(){
        try{
            DBConnection db = new DBConnection();
            conn = DBConnection.get();
            stmt = conn.createStatement();
        }
        catch(Exception e){
            System.out.println(e.getMessage());
            JOptionPane.showMessageDialog(null,e.getMessage(),"ERROR", JOptionPane.WARNING_MESSAGE);
        }
    }

    public void disconnect(){
        try {
            stmt.close();
            conn.close();
        }
        catch(Exception ex){
            System.out.println(ex.getMessage());
            JOptionPane.showMessageDialog(null,ex.getMessage(),"ERROR", JOptionPane.WARNING_MESSAGE);
        }
    }
    
    public int gettablerows(){
        int total=0;
        connect();
        try {
            
               
                SQLStatement = "SELECT COUNT(c_name) from customer";

    
           
            rset = stmt.executeQuery(SQLStatement);
            while (rset.next()) {
                total = rset.getInt(1); // store result to total
            }
            rset.close();
            disconnect();
        } catch(Exception e){
            System.out.println(e.getMessage());
            JOptionPane.showMessageDialog(null,e.getMessage(),"ERROR", JOptionPane.WARNING_MESSAGE);
        }
        return total;
    }

    public void erase(){
        for (int i=0; i<gettablerows(); i++){ // row count
            ctable.setValueAt("", i, 0);
            ctable.setValueAt("", i, 1);
        }
    }


    public void searchcustomerbyname(){
        erase();
        connect();
        int i=0;
        try{
           SQLStatement = "SELECT * FROM customer WHERE c_name LIKE '%" +c_name+"%'";
            rset = stmt.executeQuery(SQLStatement);
            while (rset.next()) {
                ctable.setValueAt(rset.getString("idcustomer"), i, 0);
                ctable.setValueAt(rset.getString("c_name"), i , 1);
                i++;
            }
            rset.close();
            disconnect();
        } catch(Exception ex){
            System.out.println(ex.getMessage());
            JOptionPane.showMessageDialog(null,ex.getMessage(),"ERROR", JOptionPane.WARNING_MESSAGE);
        }
        }
        
    }
    


